/*
 * @Description:
 * @Autor: dongjunhua
 * @Date: 2020-12-17 10:20:47
 * @LastEditors: dongjunhua
 * @LastEditTime: 2021-10-19 10:17:22
 */
import { createRouter, createWebHistory } from 'vue-router';
import { before, after } from './guards';
import Storage from '@/utils/Storage';
import Layout from '@/layout';
// import LayoutForMicroApp from '@/layout/MicroLayout.vue';
import { microAppOptions } from './micro-app';

// get routes from modules
const modulesFiles = require.context('./modules', true, /\.js$/);
// router for layout
const moduleRoutes = modulesFiles.keys().reduce((moduleRoutes, modulePath) => {
  const value = modulesFiles(modulePath);
  return [...moduleRoutes, ...value.default];
}, []);
// router for outer
const moduleRoutesForOuter = moduleRoutes.map(r => {
  return {
    path: `/${r.path}`,
    component: r.component,
    name: `${r.name}ForOuter`
  };
});
// router for micro app
const routesForMicroApp = microAppOptions.map(o => {
  return {
    path: `/${o.activeRule}/:pathMatch(.*)*`,
    component: Layout,
    name: `LayoutFor${o.name}`
  };
});

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index')
  },
  {
    path: '/auth-redirect',
    name: 'AuthRedirect',
    component: () => import('@/views/auth-redirect')
  },
  {
    path: '/401',
    name: 'NoPermission',
    component: () => import('@/views/error-page/401')
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error-page/404')
  },
  {
    path: '/i',
    name: 'Layout',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/home')
      },
      ...moduleRoutes
    ]
  },
  ...moduleRoutesForOuter,
  ...routesForMicroApp,
  {
    path: '/',
    redirect: '/i'
  },
  // catch all routes (*, /*) must now be defined using a parameter with a custom regex
  { path: '/:pathMatch(.*)*', redirect: { name: 'NotFound' } }
  // {
  //   path: '/i/:pathMatch(.*)*',
  //   name: 'LayoutForMicroApp',
  //   component: Layout
  // }
];

const router = createRouter({
  history: createWebHistory(
    window.__POWERED_BY_QIANKUN__ ? '' : process.env.VUE_APP_BASE_URI
  ),
  routes
});

// set global router guards
router.beforeEach(before);
router.afterEach(after);

const addFrameRoute = frameMenu => {
  router.addRoute('Layout', {
    path: frameMenu.routingUrl,
    component: () => import('@/views/frame'),
    name: `Frame_${frameMenu.id}`
  });
};

const getOriginalPath = path => {
  path.indexOf('/i/') === 0 && (path = path.replace(new RegExp('/i/'), ''));
  path.indexOf('i/') === 0 && (path = path.replace(new RegExp('i/'), ''));
  path.indexOf('/') === 0 && (path = path.replace(new RegExp('/'), ''));
  return path;
};

(() => {
  const subject = Storage.getLocal('subject');
  if (!subject || !subject.user || !subject.user.menuList) {
    return;
  }
  const eachMenu = (menuList, callback) => {
    menuList.forEach(m => {
      callback(m);
      m.children && m.children.length > 0 && eachMenu(m.children, callback);
    });
  };
  eachMenu(subject.user.menuList, m => {
    m.routingUrl && m.redirectUrl && addFrameRoute(m);
  });
})();

export { moduleRoutes, addFrameRoute, getOriginalPath };
export default router;
